const {
  getList,
  getDetail,
  createArticle,
  updateArticle,
  deleteArticle
} = require('../controller/blog')
const { SuccessModel, ErrorModel } = require('../model/resModel')

const loginCheck = req => {
  if (!req.session.username) {
    return new ErrorModel('尚未登录')
  }
}

const handleBlogRouter = async (req, res) => {
  const method = req.method // GET POST DELETE...

  const num = req.path.split('/').pop()
  let numParam = true
  if (isNaN(Number(num))) {
    numParam = false
  }

  // 获取博客列表
  if (method === 'GET' && req.path === '/api/blog' && !numParam) {
    let { author = '', keyword = '' } = req.query
    const blogData = await getList(author, keyword)
    return new SuccessModel(blogData)
  }
  // 获取博客详情
  if (method === 'GET' && req.path.indexOf('/api/blog') !== -1 && numParam) {
    const blogData = await getDetail(num)
    return new SuccessModel(blogData)
  }
  // 新增博客
  if (method === 'POST' && req.path === '/api/blog') {
    let loginCheck = loginCheck(req)

    if (loginCheck) {
      return loginCheck
    }

    const res = await createArticle(req.body)
    console.log(res)
    if (res.affectedRows) {
      return new SuccessModel('新增成功')
    } else {
      return new ErrorModel('新增失败')
    }
  }

  // 更新博客
  if (method === 'PUT' && req.path.indexOf('/api/blog') !== -1 && numParam) {
    let loginCheck = loginCheck(req)

    if (loginCheck) {
      return loginCheck
    }

    const res = await updateArticle(num, req.body)
    if (res.affectedRows) {
      return new SuccessModel('更新成功')
    } else {
      return new ErrorModel('更新失败')
    }
  }

  // 删除博客
  if (method === 'DELETE' && req.path.indexOf('/api/blog') !== -1 && numParam) {
    let loginCheck = loginCheck(req)

    if (loginCheck) {
      return loginCheck
    }

    let author = req.session.username

    const res = await deleteArticle(num, author)
    if (res.affectedRows) {
      return new SuccessModel(res, '删除成功')
    } else {
      return new ErrorModel(res, '删除失败')
    }
  }
}

module.exports = handleBlogRouter
